package model

import (
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
)

type Message struct { //过度Message，用来在字节流和消息刘中中转
	Type int32 //客户端请求的消息编码
	Msg  interface{}
}

// 请求的消息
const (
	SourceRequest = 1000 //客户端
	KeyGenerate   = 1001 //网关

	Ping = 2000

	ClientPem = 5000 //等待签发中心给客户端的证书
	//GatawayPem = 5001 //等待签发中心给服务端的证书
)

type PackageIntoMessage interface {
	ToBytes() []byte
	Typeis() int
}

// DeviceInfo 用于与数据库通讯
type DeviceInfo struct {
	gorm.Model
	Token   string
	Factory string
}

type CertificateInfo struct {
	gorm.Model
	Token       string
	Certificate string
}

type ClientPemRequestMessage struct {
	ID      uint
	Token   string
	Factory string
}

type GatawayClientPemRequestMessage struct {
	Device
}

//func (c *GatawayClientPemRequestMessage) ToBytes() []byte {
//	m := new(Message)
//	m.Type = GatawayPem
//	m.Msg = c
//	marshal, _ := json.Marshal(m)
//	return marshal
//}
//
//func (c *GatawayClientPemRequestMessage) Typeis() int {
//	return GatawayPem
//}

func (c *ClientPemRequestMessage) ToBytes() []byte {
	m := new(Message)
	m.Type = ClientPem
	m.Msg = c
	marshal, _ := json.Marshal(m)
	return marshal
}

func (c *ClientPemRequestMessage) Typeis() int {
	return ClientPem
}

// SourceRequestMessage 步骤1，发送资源请求
type SourceRequestMessage struct {
}

// KeyGenerateMessage 请求密钥生成中心生成密钥
type KeyGenerateMessage struct {
	ID     uint
	Token  string
	IPADDR string //客户端IP地址和端口
}

func (k *KeyGenerateMessage) ToBytes() []byte {
	m := new(Message)
	m.Type = KeyGenerate
	m.Msg = k
	marshal, _ := json.Marshal(m)
	fmt.Println(k.Token)
	return marshal
}

func (k *KeyGenerateMessage) ToDevice() *Device {
	de := new(Device)
	de.ID = k.ID
	de.Token = k.Token
	return de
}

func (k *KeyGenerateMessage) Typeis() int {
	return KeyGenerate
}

// SPAMessage 步骤11，发送单包认证信息
type SPAMessage struct {
}

func (S SPAMessage) ToBytes() []byte {
	//TODO implement me
	panic("implement me")
}

func (S SPAMessage) Typeis() int {
	//TODO implement me
	panic("implement me")
}

func (req *SourceRequestMessage) ToBytes() []byte {
	rMsg := new(Message)
	rMsg.Type = SourceRequest
	rMsg.Msg = req
	marshal, _ := json.Marshal(rMsg)
	return marshal
}

func (req *SourceRequestMessage) Typeis() int {
	return SourceRequest
}
